How to Call Functions...

What are functions...

Functions are an incredibly useful concept and I will cover them in greater detail later on, I promise. But for now let's just say functions are bits of self-contained code that take some input value(s), perform some process, and return some output. Today we shall be studying how to call functions, for what it's worth you guys have already called functions, you just didn't know that was what you are doing!

For the sake of simplicity, we are going to split functions into four basic categories:

  1. Those that take zero arguments as input.
  2. Those that take one argument as input.
  3. Those that take multiple arguments as input.
  4. Those that take optional arguments.

Before we begin though I really want to stress that these categories are not real, its an arbitrary distinction that is not founded upon anything of substance.

If that’s the case, why do it, then? I here you ask. Well, just because a distinction is not real doesn't mean it is not helpful. Basically, the reason I have made these categories is because I believe it makes the material easier to teach; a pedagogical tool, if you will.

1. Zero argument functions....

Calling zero argument functions are super simple, but they also tend to be rather uninteresting as well. The syntax:

{function name} ()

In box below I've quickly made such a function and then calling it. Boring stuff ensues.


In [1]:
# Defining the function...
def boring():
    return "ZZZZZZZZ..."

# calling said function...
boring()


Out[1]:
'ZZZZZZZZ...'

2. One argument functions....

The syntax:

{function name} ({argument})

"len" is a Python built-in function. Let's call it on a few strings and see if you can figure out what it does.


In [12]:
print ( len("a") )
print ( len("aa") )
print ( len("aaa") )


1
2
3

'len' is short for length. When you call it returns how big the object is, in the case of strings, that’s how many characters the string contains. Thus len(“12345”) returns 5.

3. Functions with Multiple Arguments

Functions that take multiple arguments can be further defined into those that require exactly n arguments and those functions that can handle an arbitrary number of arguments. We shall briefly cover both. The syntax:

{function name} ({argument}, {argument2}) 

So, to call a function that takes two arguements as imput all we do is type two arguments seperated by a comma. Let's see that in action:


In [7]:
# defining the function...
def multiply(a, b):
    return a * b # remember '*' is multiplication!

multiply(10, 25) # <-- calling the function with two arguments, 10 and 25


Out[7]:
250

What happens when you give such a function too few/too many arguments? Well, you get an error:


In [3]:
multiply(2,3,4)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-96c74c6fdf79> in <module>()
----> 1 multiply(2,3,4)

TypeError: multiply() takes 2 positional arguments but 3 were given

In [4]:
multiply(1)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-63fb0b2a3792> in <module>()
----> 1 multiply(1)

TypeError: multiply() missing 1 required positional argument: 'b'

Take care to note that the error messages you get are actually rather insightful, Python is telling you what the problem is!

Functions that take an aribitary number of arguments

Now, the syntax for a function that takes an arbitrary number of arguments is the same as the above, you just separate the values by a comma and keep on going. As a matter of fact, we have seen such a function several times already. Its called 'print'...


In [6]:
print("hello")                            # calling print with one arguement
print("hello", "world")                   # two arguments
print()                                   # calling print with zero arguments returns an empty line.
print("a", "b", "c", "d", "e", "f", "g")  # seven arguments


hello
hello world

a b c d e f g

4. Functions with optional arguments...

If a particular function argument is optional is will have two parts, a 'keyword' and a 'default value'. The syntax:

{keyword} = {value}

The 'default value' is what happens when we don't change anything, and obviously that is the bit we may want to change.

If you do give a function an optional argument make sure it is the last argument you pass the function; if you don't Python with throw and error. Anyway, here's the syntax:

{function name} ({argument}, {argument2}, {keyword} = {value} ) 

As a matter of fact, the print function we have been calling has an optional argument, this argument is called "sep" and its default value is a single 'space' character.

Let's look at the print calls above a bit more closely, did you notice that when we gave print several arguments it separated everything with a space? Well, we can change that behaviour by changing 'sep'.

For example...


In [14]:
print("a", "b", "c", "d", "e", "f", "g")            # Notice 'sep' is not defined here. Thus the default value " " is used. 
print("a", "b", "c", "d", "e", "f", "g", sep="")    # no spaces 'abc'
print("a", "b", "c", "d", "e", "f", "g", sep="__")  # double underscore, 'a__b__c' 
print("a", "b", "c", "d", "e", "f", "g", sep=",")   # comma, 'a,b,c'
print("a", "b", "c", "d", "e", "f", "g", sep="\n")  # \n = New-line, please see string lecture!


a b c d e f g
abcdefg
a__b__c__d__e__f__g
a,b,c,d,e,f,g
a
b
c
d
e
f
g

In [15]:
print(sep="", "a", "b", "c") # Keywords must be at the end!


  File "<ipython-input-15-6e9cd52157f2>", line 1
    print(sep="", "a", "b", "c") # Keywords must be at the end!
                 ^
SyntaxError: positional argument follows keyword argument

In later lectures I'll show you how to build your own functions (and why you would want to), but the purpose of this lecture was to simply get you used to seeing function calls. Trust me when I say understanding this stuff is a really useful skill to have moving forward.

Homework

In the cell below there is a function called "call me". For homework I want you to call this function with several arguments such that it returns the string:

"Dave and Jerry went to the cheese factory."

In [9]:
def call_me(a, f, d, b="", c="cheese", e=False):
    if e == True:
        return "{} and {} went to the {}{} {}".format(a, b, c, d, f)
    else:
        return "YOU SHALL NOT PASS"

# Your Code goes here... call_me(?, ?, ?, ?, ?)